package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    /**
     * 将Java对象序列化为Json，存入Redis
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 设置逻辑过期时间，将Java对象序列化为Json，存入Redis
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存空值 -> 缓存穿透
     *
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return R
     */
    public <R, ID> R queryWithPassThrough(
            String keyPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallback,
            Long time,
            TimeUnit unit
    ) {
        String key = keyPrefix + id;
        //判断redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            //存在，取出返回
            return JSONUtil.toBean(json, type);
        }
        //判断命中的是否是空值
        if (json != null) {
            return null;
        }
        //不存在，查询数据库
        R r = dbFallback.apply(id);
        if (r == null) {
            //将空值存入Redis
            this.set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //不存在，报错
            return null;
        }
        //数据库中存在，存入redis中，返回
        this.set(key, r, time, unit);
        return r;
    }

    /**
     * 逻辑过期 -> 缓存击穿
     *
     * @param keyCachePrefix
     * @param keyLockPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return R
     */
    public <R, ID> R queryWithLogicalExpire(
            String keyCachePrefix,
            String keyLockPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallback,
            Long time,
            TimeUnit unit
    ) {
        String keyCache = keyCachePrefix + id;
        String keyLock = keyLockPrefix + id;
        //判断redis中是否存在shop
        String json = stringRedisTemplate.opsForValue().get(keyCache);
        if (StrUtil.isBlank(json)) {
            //缓存未命中，直接返回空
            return null;
        }
        //缓存命中，将Json对象反序列化
        com.hmdp.entity.RedisData redisData = JSONUtil.toBean(json, com.hmdp.entity.RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        //判断是否逻辑过期
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            //未过期，直接返回商铺信息
            return r;
        }
        //过期，执行缓存重建
        //尝试获取互斥锁
        boolean isLock = this.tryLock(keyLock);
        //获取锁成功
        if (isLock) {
            //再次检查Redis是否过期
            json = stringRedisTemplate.opsForValue().get(keyCache);
            if (StrUtil.isNotBlank(json)) {
                //未过期，直接返回
                redisData = JSONUtil.toBean(json, com.hmdp.entity.RedisData.class);
                r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
                return r;
            }
            //过期，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //写入Redis
                    this.setWithLogicalExpire(keyCache, r1, time, unit);
                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {
                    this.unLock(keyLock);
                }
            });
        }
        //返回过期的商铺信息
        return r;
    }

    /**
     * 互斥锁 -> 缓存击穿
     *
     * @param keyCachePrefix
     * @param keyLockPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return R
     */
    public <R, ID> R queryWithMutex(
            String keyCachePrefix,
            String keyLockPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallback,
            Long time,
            TimeUnit unit
    ) {
        String keyCache = keyCachePrefix + id;
        String keyLock = keyLockPrefix + id;
        //判断redis中是否存在shop
        String json = stringRedisTemplate.opsForValue().get(keyCache);
        if (StrUtil.isNotBlank(json)) {
            //存在，取出返回
            return JSONUtil.toBean(json, type);
        }
        //判断命中的是否是空值
        if (json != null) {
            return null;
        }
        R r = null;

        //实现重建缓存
        try {
            //不存在，尝试获取互斥锁
            if (!tryLock(keyLock)) {
                //获取失败，重试
                Thread.sleep(50);
                return queryWithMutex(keyCachePrefix, keyLockPrefix, id, type, dbFallback, time, unit);
            }
            //获取成功，再次判断redis中是否存在shop
            json = stringRedisTemplate.opsForValue().get(keyCache);

            if (StrUtil.isNotBlank(json)) {
                //存在，取出返回
                return JSONUtil.toBean(json, type);
            }
            //获取成功，但redis不存在shop，根据 id 查询数据库
            r = dbFallback.apply(id);
            //模拟重建延迟
            Thread.sleep(200);
            if (r == null) {
                //将空值存入Redis
                this.set(keyCache, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                //不存在，报错
                return null;
            }
            //数据库中存在，存入redis中，返回
            this.set(keyCache, r, time, unit);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } finally {
            //释放互斥锁
            unLock(keyLock);
        }
        return r;
    }

    /**
     * 加锁
     *
     * @param key
     * @return boolean
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, LOCK_SHOP_VALUE, LOCK_SHOP_TTL, TimeUnit.SECONDS);
        //防止自动拆箱后的空指针问题
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

}